<template>
  <a-card class="general-card" title="文章管理" :bordered="false">
    <a-row style="margin-bottom: 16px">
      <a-col :span="4">
        <a-tree blockNode :data="treeData" @select="handleCateChange" />
      </a-col>
      <a-col :span="20">
        <a-card title="" :bordered="false">
          <PickSearchColumn  :rowSpan="isNormal ? 0 : 12"  :columns="columnsSearch" @reset="(val) => {articleParams = {...articleParams, ...val}}" @search="(val) => {articleParams = {...articleParams, ...val}}">
          </PickSearchColumn>
          <a-button type="primary" style="margin-bottom: 16px;" @click="add">添加</a-button>
          <PickTablePage  :radio="isNormal ? false : true" :bordered="true" @selectTableChange="chosenArticle" :checkbox="isNormal ? false : true" ref="tablePageRef" :columns="columnsTable" :methods="sortMethods" :api="getArticle" :border="true" :apiParams="articleParams">
            <template #openStatus="{ data }">
              <a-switch v-model="data.openStatus" @change="changeSwitch(data)">
                <template #checked>展示</template>
                <template #unchecked>隐藏</template>
              </a-switch>
            </template>
            <template #operation="{ data }">
              <a-button style="margin-right: 10px;" @click="handleEditor(data)" type='text' status="warning">编辑</a-button>
              <a-button @click="handleDelete(data)" type="text" status="danger">删除</a-button>
            </template>
          </PickTablePage>
        </a-card>
      </a-col>
    </a-row>

    <!--添加文章模态框-->
    <a-modal v-model:visible="articleFormData.modalVisible" :align-center="false" title-align="start" :width="1100" draggable @ok="handleConfirm" @cancel="handleClose">
      <template #title> {{articleFormData.modalType?'编辑文章':'添加文章'}} </template>
      <a-form ref="formRef" :model="articleFormData.articleForm" layout="horizontal" auto-label-width>
        <a-form-item field="title" label="文章标题" :rules="[REQUIRED]">
          <a-input v-model="articleFormData.articleForm.title" :style="{ width: '380px' }"/>
        </a-form-item>
        <a-form-item field="categoryId" label="文章分类" :rules="[REQUIRED]">
          <a-tree-select v-model="articleFormData.articleForm.categoryId" :data="treeDataDefault" placeholder="请选择" :style="{ width: '380px' }" @change="handleCheckChange"></a-tree-select>
        </a-form-item>
        <a-form-item field="sort" label="文章排序" :rules="[REQUIRED]">
          <a-input-number v-model="articleFormData.articleForm.sort" :style="{ width: '200px' }"></a-input-number>
        </a-form-item>
        <a-form-item filed="content" label="文章内容" :rules="[REQUIRED]">
          <Editor :initValue="articleFormData.articleForm.content" @getEditorContent="onEditorChange" :key="editorKey"></Editor>
        </a-form-item>
        <a-form-item field="openStatus" label="是否展示" :rules="[REQUIRED]">
          <a-switch v-model="articleFormData.articleForm.openStatus">
            <template #checked>展示</template>
            <template #unchecked>隐藏</template>
          </a-switch>
        </a-form-item>
      </a-form>
    </a-modal>

  </a-card>
</template>

<script setup lang="ts">
  
  import { PickSearchColumn, PickTablePage } from '@pickmall/ui-v3-components';
  import{ getArticleCategory, getArticle, updateArticleStatus, seeArticle, delArticle, saveArticle, updateArticle } from '@/api/operation';
  import { ref, onMounted, reactive } from 'vue';
  import { MethodsRule, ColumnsDataRule, SearchRule } from '@/types/global';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { Message } from '@arco-design/web-vue';
  import { VARCHAR255, REQUIRED, VARCHAR20, MOBILE } from '@/utils/validator';
  import Editor from '@/components/editor/index.vue';

  const props = defineProps({
    templateModel: {
      type: String,
      default: 'normal',
    },
  })
  const emit = defineEmits(['selectTableChange']);
  const isNormal: boolean = props.templateModel === 'normal';

  // 获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const treeData = ref();
  const treeDataDefault = ref();
  const formRef = ref();
  const columnsSearch: Array<SearchRule> = [
    {label: '文章标题', model: 'title', disabled: false, input: true,},
  ];
  const tablePageRef = ref<any>();
  // 搜索框初始化对象
  const searchForm = ref({});
  // 查询文章列表自定义参数
  const articleParams = ref({
    categoryId: ''
  });
  const columnsTable: ColumnsDataRule[] = [
    {title: '分类名称', dataIndex: 'articleCategoryName' ,width: 150,},
    {title: '文章标题', dataIndex: 'title',width: 250,},
    {title: '是否显示', dataIndex: 'openStatus', width: 150, slot: true, slotTemplate: 'openStatus'},
    {title: '排序', dataIndex: 'sort', width: 50},
  ];
  const sortMethods: MethodsRule = {
    title: '操作',
    width: 200,
    fixed: 'right',
    methods: [
      {title: '操作', slot: true, slotTemplate: 'operation'}
    ],
  };
  interface formInterface {
    modalVisible: boolean;
    modalType: number | string;
    articleForm: any;
    treeValue: any;
  }
  const articleFormData :formInterface = reactive({
    modalVisible: false,  // 模态框是否显示
    modalType: 0, // 添加或编辑标识（0添加 1编辑）
    // 添加或编辑表单初始化数据
    articleForm: {
      openStatus: false,
      title: "",
      categoryId: "",
      sort: 1,
      content: null,
      id: "",
    },
    // 选择的分类
    treeValue: ""
  });
  const editorKey = ref(1);

  // 文章分类格式化方法
  const getTree = (tree = []) => {
    const arr = [] as Array<any>;
    if (!!tree && tree.length !== 0) {
      tree.forEach((item: any) => {
        const obj = {
          title: item.articleCategoryName,
          key: item.id,
          children: getTree(item.children), // 递归调用
        };
        arr.push(obj);
      });
    }
    return arr;
  };
  // 获取全部文章分类
  const getAllList = (parentId: number | string) => {
    getArticleCategory(parentId).then(res => {
      if (res.data.success) {
        treeDataDefault.value = getTree(res.data.result);
        treeData.value = getTree(res.data.result);
        treeData.value.unshift({title: '全部', key: '', children: []});
      }
    })
  };
  // 选择分类回调（点击树节点时触发）
  const handleCateChange = (data: any) => {
    articleParams.value.categoryId = data.join(',');
    tablePageRef.value?.init();
  };
  // 文章分类的选择事件
  const handleCheckChange = (value: any) => {
    articleFormData.articleForm.categoryId = value;
  };
  // 是否展示文章
  const changeSwitch = (data: any) => {
    const params = { status: data.openStatus };
    updateArticleStatus(data.id, params).then(res => {
      if (res.data.success) {
        Message.success('操作成功！');
      }
    })
  };
  // 添加文章modal
  const add = () => {
    articleFormData.modalType = 0;
    articleFormData.articleForm.treeValue = "";
    formRef.value.resetFields();
    delete articleFormData.articleForm.id;
    articleFormData.modalVisible = true;
    articleFormData.articleForm.content = ""
    editorKey.value += 1;
  };
  // 富文本change事件
  const onEditorChange = (arr: any, html: any) => {
    articleFormData.articleForm.content = html;
  };
  // 添加文章确认
  const handleConfirm = () => {
    if (articleFormData.modalType === 0) {
      // 添加文章
      // 避免编辑后传入id等数据 记得删除
      delete articleFormData.articleForm.id;
      delete articleFormData.articleForm.treeValue;
      saveArticle(articleFormData.articleForm).then(res => {
        if (res.data.success) {
          Message.success('操作成功！');
          tablePageRef.value?.init();
        }
      })
    } else if (articleFormData.modalType === 1) {
      // 编辑文章
      updateArticle(articleFormData.articleForm).then(res => {
        if (res.data.success) {
          Message.success('操作成功！');
          tablePageRef.value?.init();
        }
      })
    }
  };
  // 添加文章取消
  const handleClose = () => {

  }
  // 编辑文章modal
  const handleEditor = (data: any) => {
    articleFormData.modalType = 1;
    articleFormData.treeValue = "";
    formRef.value.resetFields();
    seeArticle(data.id).then(res => {
      if (res.data.success) {
        articleFormData.modalVisible = true;
        editorKey.value += 1;
        articleFormData.articleForm.categoryId = res.data.result.categoryId;
        articleFormData.articleForm.treeValue = data.articleCategoryName;
        articleFormData.articleForm.id = data.id;
        articleFormData.articleForm.content = res.data.result.content;
        articleFormData.articleForm.title = res.data.result.title;
        articleFormData.articleForm.sort = res.data.result.sort;
        articleFormData.articleForm.openStatus = res.data.result.openStatus;
      }
    })
  };
  // 删除
  const handleDelete = (data: any) => {
    modal.confirm({
      title: '确认删除',
      content: '您确认要删除么?',
      alignCenter: false,
      onOk: async () => {
        const res = await delArticle(data.id);
        if (res.data.success) {
          Message.success('操作成功！');
          tablePageRef.value?.init();
        }
      },
    });
  };
  function chosenArticle(val: any) {
    emit('selectTableChange', { ...val[0], ___type: 'pages' })
  }
  const passContent = (value: string): void => {
    articleFormData.articleForm.content = value;
  };

  // 初始化
  onMounted(() => {
    getAllList(0);
  })
</script>

<style scoped lang="scss">



</style>
